﻿using System;
using System.IO;
using System.Net;
using CSSetDesktopWallpaper;
using KonachanChanger.API;

namespace KonachanChanger
{
    public static class WallpaperWrapper
    {
        public static void SetImage(string filename)
        {
            CSSetDesktopWallpaper.WallpaperStyle style = KonachanChanger.Data.LocalDb.GetInstance().Prefs.WallpaperStyle;
            if ((style == WallpaperStyle.Fill|| style == WallpaperStyle.Fit) && !Wallpaper.SupportFitFillWallpaperStyles)
                Wallpaper.SetDesktopWallpaper(filename, WallpaperStyle.Center);
            else
                Wallpaper.SetDesktopWallpaper(filename, style);
         }

        public static void SetPostAsWallPaper(post Post)
        {
            IsSettingWallpaper = true;
            SettingWallpaper = Post;
            try
            {
                var image = Post.Download();

                if (SettingWallpaper == Post)
                {
                    SetImage(image);
                    CurrentWallpaper = Post;
                    IsSettingWallpaper = false;
                }
            }
            catch (WebException)
            {
                IsSettingWallpaper = false;
            }
            catch (InvalidDataException)
            {
                IsSettingWallpaper = false;
            }
            //if (File.Exists(Post.ImagePath))
            //{
            //    SetImage(Post.ImagePath);
            //    CurrentWallpaper = Post;
            //}
            //else
            //{
            //    IsSettingWallpaper = true;
            //    webClient.DownloadFileAsync(new Uri(Post.file_url), Post.ImagePath, Post);
            //    CurrentWallpaper = Post;
            //}
        }

        public static Boolean IsSettingWallpaper { get; private set; }

        public static post CurrentWallpaper { get; private set; }
        public static post SettingWallpaper { get; private set; }
    }
}
